import { Component, OnInit, OnChanges, Input } from '@angular/core';
import { Assembly, AssemblyStyles, AssemblyValidators } from '../../../fb-design.model';
import { HttpClient } from '@angular/common/http';
import { FormGroup } from '@angular/forms';

@Component({
    selector: 'qk-input',
    template: `
        <ng-container [formGroup]="form">
            <ng-container *ngIf="!assembly.configs.autocomplete">
                <input pInputText id="{{assembly.id}}" [ngStyle]="assembly.attributes.style" [formControlName]="assembly.id" 
                    placeholder="{{assembly.configs.placeholder}}"/>
                <div *ngIf="formErrors[assembly.id]" class="alert alert-danger">
                    <i class="fa fa-times"></i>{{formErrors[assembly.id]}}
                </div>
            </ng-container>
            <ng-container *ngIf="assembly.configs.autocomplete">
                <p-autoComplete id="{{assembly.id}}" [inputStyle]="assembly.attributes.style" [formControlName]="assembly.id"
                    [minLength]="1" delay="500" [suggestions]="results" (completeMethod)="search($event)"></p-autoComplete>  
                <div *ngIf="formErrors[assembly.id]" class="alert alert-danger">
                    <i class="fa fa-times"></i>{{formErrors[assembly.id]}}
                </div>
            </ng-container>
        </ng-container>
    `,
    styles: [`
        .alert-danger{
            background-color:#f8b7bd;
            margin-top:1px;
            padding:0.429em;
            color:#212121;
            z-index:999;
            position:relative;
        }
    `],
    providers: []
})
export class QkInput implements OnChanges, OnInit {
    @Input() assembly: Assembly;
    @Input() form: FormGroup;
    @Input() formErrors: any = {};
    @Input() mode: number;

    results : any; 
    constructor(private http: HttpClient) { }

    ngOnInit() {
        if(this.mode == 2){
            if(1 == this.assembly.authCode){//只读
                $("#mask_"+this.assembly.id).css({'z-index': 1, 'opacity': 0.5, 'background-color':'lightgray'});
            }else if(0 == this.assembly.authCode){//没有权限
                $("#mask_"+this.assembly.id).css({'z-index': 1, 'background-color':'lightgray'});
            }
        }
        
    }

    ngOnChanges() { }

    ngDoCheck() {
        this.assembly.attributes.refreshStyle();
    }

    //自动补全
    search(event){
        let query = event.query;
        let sql = this.assembly.configs.completeSQL;
        let url = this.assembly.configs.completeURL;
        if(url && sql && query){
            this.http.get('/'+ url+ '/api/interface/autocomplete?query='+ query +'&sql=' + encodeURI(sql)).subscribe(data => {
                this.results = data;
            });
        }

    }
    
}